import React from "react";
import {Redirect, Route, Switch} from 'react-router-dom';
import allPages from "../pages/manage/config"
import RouteWrapper from "./routeWrapper";
import {useRecoilValue} from "recoil";
import {userInfoState} from "../store/user";
import NotFound from "../pages/error/nouFound";
import Forbidden from "../pages/error/forbidden";

/**
 * 路由组件
 */
const Routes = (props: RoutesProps) => {
    const {routesConf} = props;
    const userInfo = useRecoilValue(userInfoState);
    const isLogin = !!userInfo; // 不为空表示登录

    /**
     * 登录检查
     *
     * 如果当前未登录则跳转到登录页面
     * 如果没有许可证则跳转到 403 页面
     *
     * @param routesPermits 路由许可证，如果为空则不进行校验
     * @param component 路由组件
     */
    const requireLogin = (routesPermits: string | undefined, component: React.ReactElement) => {
        // 未登录重定向到登录页
        if (!isLogin) {
            return <Redirect to={'/manage/login'}/>;
        }

        // 如果没有许可证权限则跳转到 403 页面
        if (!!routesPermits && (!(userInfo?.permits) || !(userInfo?.permits.includes(routesPermits))))
            return <Forbidden/>;

        return component;
    };

    // 创建菜单
    const createMenu = (r: IRoutes) => {

        // 路由
        const route = (r: IRoutesBase) => {
            const component = r.component && allPages[r.component];
            return (
                <Route
                    key={r.path}
                    exact
                    path={r.path}
                    render={(props: any) => {
                        // 重新包装组件
                        const wrapper = (
                            <RouteWrapper {...{...props, component, route: r}} />
                        );
                        return r.requireLogin ? requireLogin(r.requirePermits, wrapper) : wrapper;
                    }}
                />
            );
        };

        // 子路由
        const subRoute = (r: IRoutes): any =>
            r.subs && r.subs.map((subR: IRoutes) => (subR.subs ? subRoute(subR) : route(subR)));

        return r.component ? route(r) : subRoute(r);
    };

    return (
        <Switch>
            {/*创建路由*/}
            {(routesConf as IRoutes[]).map(conf => createMenu(conf))}
            {/*不存在跳转到404页面*/}
            <Route render={() => <NotFound/>}/>
        </Switch>
    )
}

export default Routes;

export interface RoutesProps {

    /**
     * 路由数组
     */
    routesConf: IRoutes[];

}

export interface IRoutesBase {

    /**
     * 路由地址
     */
    path: string;

    /**
     * 标题
     */
    title: string;

    /**
     * 组件名称
     */
    component?: string;

    /**
     * 查询参数
     */
    query?: string;

    /**
     * 需要指定的许可证,才可以访问
     */
    requirePermits?: string;

    /** 是否登录校验，false不进行校验（访客） */
    requireLogin?: boolean;
}

export interface IRoutes extends IRoutesBase {

    /**
     * 子级路由
     */
    subs?: IRoutes[];
}
